package com.cloud.phone.task.whatsapp;

import android.graphics.Bitmap;
import android.graphics.Rect;
import android.view.accessibility.AccessibilityNodeInfo;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.cloud.phone.base.BaseApp;
import com.cloud.phone.constants.Constants;
import com.cloud.phone.task.BaseTask;
import com.cloud.phone.task.MsgTaskManger;
import com.cloud.phone.task.TaskManager;
import com.cloud.phone.task.taskCongfig.FindIdResouresConfig;
import com.cloud.phone.task.taskCongfig.WhatsAppNodeIdConfig;
import com.cloud.phone.task.taskCongfig.WhatsAppTypeConfig;
import com.cloud.phone.tools.AccessibilityTool;
import com.cloud.phone.tools.LogUtils;
import com.cloud.phone.tools.MyUtils;
import com.cloud.phone.utils.AppUtils;
import com.cloud.phone.utils.BingTopDama;
import com.cloud.phone.utils.HuaweiObsUtils;
import com.cloud.phone.utils.ImageCropper;
import com.cloud.phone.utils.MediaRefreshHelper;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class WhatsAppTask extends BaseTask {
    public WhatsAppTaskDealTool whatsAppTaskDealTool;
    private WhatsAppUserInfo whatsAppUserInfo;
    private String whatsAppChatImageName="whatsApp_chat";

    @Override
    public void doTask() throws InterruptedException {
        if (whatsAppTaskDealTool == null) {
            whatsAppTaskDealTool = new WhatsAppTaskDealTool(this);
        }
        //只处理状态为运行开始的
        //设置状态为运行中，防止被新来的节点刷新事件覆盖
        onTaskRunning();
        //主线程
        //处理本次节点的对应流程，每个流程结束后都应该更改task对应的状态
        dealWithTask();
    }




    SimpleDateFormat dateFormat=new SimpleDateFormat("HH:mm:ss");
    private  void dealWithTask() throws InterruptedException {
        if(FindIdResouresConfig.permissionPackage.equals(AccessibilityTool.getInstance().getCurrentPagePackageName(service))){
            whatsAppTaskDealTool.allowPermission();
            Thread.sleep(2000);
            changeTaskStatusToStart();
            return;
        }
        if (AccessibilityTool.getInstance().checkIsEnterInWhatsApp(service)) {
            //已在whatsApp页面
            try {
                doTaskWithTaskType();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            if(TaskManager.getInstance().getCurrentTask()==null||service==null){
                return;
            }
            String pkgName=AccessibilityTool.getInstance().getCurrentPagePackageName(service);
            MsgTaskManger.showLog(dateFormat.format(new Date())+"-中未在whatsApp中：taskType="+currentTaskType+"/当前app包名："+pkgName);
            if(MyUtils.isEmpty(pkgName)){
                MsgTaskManger.showLog("获取不到当前包名，重新刷新当前task状态");
                Thread.sleep(2000);
                changeTaskStatusToStart();
                return;
            }
            //不在whatsApp页面时
            if (AppUtils.Companion.isAppInstall(BaseApp.app.getApplicationContext(), Constants.whatsAppPackageName)) {
                AppUtils.Companion.launchApp(BaseApp.app.getApplicationContext(), Constants.whatsAppPackageName);
                Thread.sleep(2000);
                changeTaskStatusToStart();
            }else{
                onTaskErr("未安装whatsApp");
            }
        }
    }

    private synchronized void doTaskWithTaskType() throws InterruptedException {
        switch (currentTaskType) {
            case WhatsAppTypeConfig.WHATS_TYPE_UPDATE_USER_INFO:
                updateUserInfo();
                break;
            case WhatsAppTypeConfig.WHATS_TYPE_UPDATE_CONVERSATION_LIST:
                updateConversationList();
                break;
            case WhatsAppTypeConfig.WHATS_TYPE_UPDATE_SEND_MESSAGE_TO:
                sendMsgToUser();
                break;
            case WhatsAppTypeConfig.WHATS_TYPE_GET_MESSAGE_HISTORY:
                getMsgHistory(15);
                break;
            case WhatsAppTypeConfig.WHATS_TYPE_EDIT_NICKNAME:
                editNickName();
                break;
        }
    }


    /**
     * 需要修改的昵称集合
     */
    public static List<String> nickNameNeedEdit =new ArrayList<>();
    private void editNickName() throws InterruptedException {
        if(MyUtils.isEmpty(nickNameNeedEdit)){
            onTaskErr("需要被修改的昵称为空");
            return;
        }
        boolean hasSameNameInNickNameList=checkHasSameInList(nickNameNeedEdit);
        for(String nickName:nickNameNeedEdit){
            if(!Constants.whatsAppPackageName.equals(AccessibilityTool.getInstance().getCurrentPagePackageName(service))){
                onTaskErr("未进入WhatsApp聊天页面");
                return;
            }
            boolean isCurrentItemIsGroup=false;
            boolean isChangeConversationAc=whatsAppTaskDealTool.isChangeConversationAcMain(true);
            if(isChangeConversationAc){
                String strGroupNames = SPUtils.getInstance().getString(WhatsAppTypeConfig.groupOrGgType);
                GroupOrGgNameList groupOrGgNameList=null;
                //先获取循环列表时的初始群组和公告名称缓存列表
                if(!MyUtils.isEmpty(strGroupNames)){
                    MsgTaskManger.showLog("群组列表："+strGroupNames);
                    groupOrGgNameList=GsonUtils.fromJson(strGroupNames,GroupOrGgNameList.class);
                }

                List<AccessibilityNodeInfo> chatList = whatsAppTaskDealTool.findNodesPlusById(WhatsAppNodeIdConfig.chatListItem);
                for(AccessibilityNodeInfo chatItem:chatList){
                   if(groupOrGgNameList!=null&&!MyUtils.isEmpty(groupOrGgNameList.getGroupOrGgNameList())){
                       for(String groupNameItem: groupOrGgNameList.getGroupOrGgNameList()){
                           if(groupNameItem.equals(nickName)){
                               MsgTaskManger.showLog("当前的groupNameItem:"+groupNameItem);
                               isCurrentItemIsGroup=true;
                               groupOrGgNameList.getGroupOrGgNameList().remove(groupNameItem);
                               break;
                           }
                       }
                   }
                   //当前这个是群组类型且没有相同的名称时，跳过本条的长按设置昵称操作
                   if(!hasSameNameInNickNameList&&isCurrentItemIsGroup){
                       MsgTaskManger.showLog("是群组类型，continue:"+nickName);
                       break;
                   }

                    List<AccessibilityNodeInfo> singleChatNode = chatItem.findAccessibilityNodeInfosByViewId(WhatsAppNodeIdConfig.singleChatHeadId);
                    if(!whatsAppTaskDealTool.isNodeExist(singleChatNode)){
                        continue;
                    }
                    ConversationItemBean conversationItemBean=new ConversationItemBean();
                    List<AccessibilityNodeInfo> nameNodes = chatItem.findAccessibilityNodeInfosByViewId(WhatsAppNodeIdConfig.contactNameInChatListNode);
                    List<AccessibilityNodeInfo> msgNodes = chatItem.findAccessibilityNodeInfosByViewId(WhatsAppNodeIdConfig.conversationMsgNode);
                    List<AccessibilityNodeInfo> conversationsRowDateNode = chatItem.findAccessibilityNodeInfosByViewId(WhatsAppNodeIdConfig.conversationsRowDateNode);
                    List<AccessibilityNodeInfo> conversationsUnReadCountNode = chatItem.findAccessibilityNodeInfosByViewId(WhatsAppNodeIdConfig.conversationsUnReadCountNode);
                    if(whatsAppTaskDealTool.isNodeExist(nameNodes)&&whatsAppTaskDealTool.isNodeExist(msgNodes)&&whatsAppTaskDealTool.isNodeExist(conversationsRowDateNode)){
                        String nickNameInList=nameNodes.get(0).getText().toString();
                        String msgInList=msgNodes.get(0).getText().toString();
                        String dateInList=conversationsRowDateNode.get(0).getText().toString();
                        int unReadCount=0;
                        if(whatsAppTaskDealTool.isNodeExist(conversationsUnReadCountNode)){
                            String textUnReadText=conversationsUnReadCountNode.get(0).getText().toString();
                            if(MyUtils.isEmpty(textUnReadText)) {
                                textUnReadText = "0";
                            }
                            unReadCount=Integer.parseInt(textUnReadText);
                        }
                        conversationItemBean=new ConversationItemBean();
                        conversationItemBean.setNickName(nickNameInList);
                        conversationItemBean.setMessage(msgInList);
                        conversationItemBean.setUpdateDate(dateInList);
                        conversationItemBean.setUnReadCount(unReadCount);

                        if(conversationItemBean.getNickName().equals(nickName)){
                            //找到需要修改的itemNode
                            whatsAppTaskDealTool.longClickXy(chatItem);
                            Thread.sleep(3000);
                            if(!Constants.whatsAppPackageName.equals(AccessibilityTool.getInstance().getCurrentPagePackageName(service))){
                                onTaskErr("未进入WhatsApp聊天页面");
                                return;
                            }
                            AccessibilityNodeInfo searchId = whatsAppTaskDealTool.findNodeFirstById(WhatsAppNodeIdConfig.menuItemSearchNodeId);
                            AccessibilityNodeInfo menuItemNodeId = whatsAppTaskDealTool.findNodeFirstById(WhatsAppNodeIdConfig.topRightMenuNodeId);
                            if(searchId!=null&&menuItemNodeId!=null){
                                whatsAppTaskDealTool.clickXy(menuItemNodeId);
                                showLogAndTsPrint("点击右上角菜单");
                                Thread.sleep(2000);
                                if(!Constants.whatsAppPackageName.equals(AccessibilityTool.getInstance().getCurrentPagePackageName(service))){
                                    onTaskErr("未进入WhatsApp聊天页面");
                                    return;
                                }
                                List<AccessibilityNodeInfo> menuItemNodes = whatsAppTaskDealTool.findNodesById(WhatsAppNodeIdConfig.menuItemNodeId);
                                if(whatsAppTaskDealTool.isNodeExist(menuItemNodes)){
                                    if(menuItemNodes.size()>2&&menuItemNodes.get(1).getText().equals("查看联系人")){
                                        whatsAppTaskDealTool.clickXy(menuItemNodes.get(1));
                                        showLogAndTsPrint("点击查看联系人");
                                        Thread.sleep(2000);
                                        if(!Constants.whatsAppPackageName.equals(AccessibilityTool.getInstance().getCurrentPagePackageName(service))){
                                            onTaskErr("未进入WhatsApp聊天页面");
                                            return;
                                        }
                                        //进入联系人详情页面
                                         menuItemNodeId = whatsAppTaskDealTool.findNodeFirstById(WhatsAppNodeIdConfig.topRightMenuNodeId);
                                        AccessibilityNodeInfo personalTelNode = whatsAppTaskDealTool.findNodeFirstPlusById(WhatsAppNodeIdConfig.personalDetailsTelNodeId);
                                        if(menuItemNodeId!=null&&personalTelNode!=null){
                                            whatsAppTaskDealTool.clickXy(menuItemNodeId);
                                            Thread.sleep(2000);
                                            if(!Constants.whatsAppPackageName.equals(AccessibilityTool.getInstance().getCurrentPagePackageName(service))){
                                                onTaskErr("未进入WhatsApp");
                                                return;
                                            }
                                            menuItemNodes = whatsAppTaskDealTool.findNodesById(WhatsAppNodeIdConfig.menuItemNodeId);
                                            if(menuItemNodes.size()>2&&menuItemNodes.get(1).getText().equals("编辑")){
                                                whatsAppTaskDealTool.clickXy(menuItemNodes.get(1));
                                                Thread.sleep(2000);
                                                if(!Constants.whatsAppPackageName.equals(AccessibilityTool.getInstance().getCurrentPagePackageName(service))){
                                                    onTaskErr("未进入WhatsApp");
                                                    return;
                                                }
                                                AccessibilityNodeInfo phoneNumBt = whatsAppTaskDealTool.findNodeFirstById(WhatsAppNodeIdConfig.phoneNumEtNodeId);
                                                AccessibilityNodeInfo countryCodeFieldId = whatsAppTaskDealTool.findNodeFirstById(WhatsAppNodeIdConfig.countryCodeFieldId);
                                                AccessibilityNodeInfo firstNameEtNode = whatsAppTaskDealTool.findNodeFirstById(WhatsAppNodeIdConfig.firstNameField);
                                                AccessibilityNodeInfo lastNameEtNode = whatsAppTaskDealTool.findNodeFirstById(WhatsAppNodeIdConfig.lastNameField);
                                                if(phoneNumBt!=null&&countryCodeFieldId!=null){
                                                    showLogAndTsPrint("设置新的昵称");
                                                    try {
                                                        String countryCode="";
                                                        String phoneNum="";
                                                        String firstName="";
                                                        String secondName="";
                                                        if(countryCodeFieldId.getText()!=null) {
                                                            countryCode = countryCodeFieldId.getText().toString();
                                                        }
                                                        if(phoneNumBt.getText()!=null) {
                                                            phoneNum = phoneNumBt.getText().toString().trim();
                                                            phoneNum=phoneNum.replace(" ","");
                                                        }
                                                        if(firstNameEtNode.getText()!=null) {
                                                            firstName = firstNameEtNode.getText().toString();
                                                        }
                                                        if(lastNameEtNode.getText()!=null) {
                                                            secondName = lastNameEtNode.getText().toString();
                                                        }


                                                        String allRealName=firstName+" "+secondName;
                                                        if(MyUtils.isEmpty(firstName)){
                                                            allRealName=secondName;
                                                        }else if(MyUtils.isEmpty(secondName)){
                                                            allRealName="";
                                                        }else{
                                                            if(firstName.equals("名字")&&secondName.equals("姓氏")){
                                                                allRealName="";
                                                            }
                                                        }
                                                        String currentCountryCode="";
                                                        if(!MyUtils.isEmpty(countryCode)&&countryCode.contains(" ")){
                                                            currentCountryCode=countryCode.split(" ")[1];
                                                        }
                                                        String needSetFirstName=currentCountryCode+"-"+phoneNum+"_";
                                                        String needSetSecondName=allRealName;
                                                        whatsAppTaskDealTool.setNodeText(firstNameEtNode,needSetFirstName);
                                                        Thread.sleep(200);
                                                        whatsAppTaskDealTool.setNodeText(lastNameEtNode,needSetSecondName);
                                                        Thread.sleep(500);
                                                        AccessibilityNodeInfo saveBtNode = whatsAppTaskDealTool.findNodeFirstById(WhatsAppNodeIdConfig.saveBtNode);
                                                        if(saveBtNode!=null){
                                                            whatsAppTaskDealTool.clickXy(saveBtNode);
                                                            Thread.sleep(2000);
                                                            if(!Constants.whatsAppPackageName.equals(AccessibilityTool.getInstance().getCurrentPagePackageName(service))){
                                                                onTaskErr("未进入WhatsApp");
                                                                return;
                                                            }
                                                            menuItemNodeId = whatsAppTaskDealTool.findNodeFirstById(WhatsAppNodeIdConfig.topRightMenuNodeId);
                                                            personalTelNode = whatsAppTaskDealTool.findNodeFirstPlusById(WhatsAppNodeIdConfig.personalDetailsTelNodeId);
                                                            if(menuItemNodeId!=null&&personalTelNode!=null){
                                                                whatsAppTaskDealTool.backOnce();
                                                                Thread.sleep(1000);
                                                            }
                                                        }
                                                    }catch (Exception e){
                                                        e.printStackTrace();
                                                        showLogAndTsPrint("获取信息失败");
                                                    }
                                                }

                                            }
                                        }
                                    }else{
                                        dealWithGroupItem(nickName);
                                    }
                                }else{
                                    dealWithGroupItem(nickName);
                                }
                            }else{
                                whatsAppTaskDealTool.backOnce();
                                Thread.sleep(1000);
                            }
                        }
                    }
                }
            }else{
                MsgTaskManger.showLog("无法切换到对话页面");
            }
        }
        nickNameNeedEdit.clear();
        onTaskFinish();
    }

    /**
     * 先检测下是否有相同名称的在列表中
     * @param nickNameNeedEdit
     * @return
     */
    private boolean checkHasSameInList(List<String> nickNameNeedEdit) {
        if(MyUtils.isEmpty(nickNameNeedEdit)){
            return false;
        }
        List<String> copyList = new ArrayList<>(nickNameNeedEdit);
        for(int i=0;i<nickNameNeedEdit.size();i++){
            String currentNickName=nickNameNeedEdit.get(i);
            for(int j=0;j<copyList.size();j++){
                if(i==j){
                    continue;
                }
                String copyItem=copyList.get(j);
                if(copyItem.equals(currentNickName)){
                    return true;
                }
            }

        }
        return false;
    }

    private void dealWithGroupItem(String nickName) throws InterruptedException {
        if(!Constants.whatsAppPackageName.equals(AccessibilityTool.getInstance().getCurrentPagePackageName(service))){
            onTaskErr("未进入WhatsApp");
            return;
        }
        //对应的item为群组或公告
        String groupNameStr = SPUtils.getInstance().getString(WhatsAppTypeConfig.groupOrGgType);
        GroupOrGgNameList groupOrGgNameListItems=null;
        if(!MyUtils.isEmpty(groupNameStr)){
            groupOrGgNameListItems=GsonUtils.fromJson(groupNameStr,GroupOrGgNameList.class);
        }else{
            groupOrGgNameListItems=new GroupOrGgNameList();
        }
        boolean hasAddInList=false;
        for(int i=0;i<groupOrGgNameListItems.getGroupOrGgNameList().size();i++){
            if(groupOrGgNameListItems.getGroupOrGgNameList().get(i).equals(nickName)){
                hasAddInList=true;
                break;
            }
        }
        if(!hasAddInList){
            groupOrGgNameListItems.getGroupOrGgNameList().add(nickName);
            SPUtils.getInstance().put(WhatsAppTypeConfig.groupOrGgType,GsonUtils.toJson(groupOrGgNameListItems));
        }
        showLogAndTsPrint("该聊天为群组或公告类型");
        whatsAppTaskDealTool.backOnce();
        Thread.sleep(1000);
        whatsAppTaskDealTool.backOnce();
        showLogAndTsPrint("返回初始状态");
        Thread.sleep(1000);
    }


    /**
     * 获取消息历史记录
     * 传1则获取当前屏的记录
     *
     */
    int IS_SELF=1;
    int IS_TO_CHAT_USER=0;
    int IS_OTHER_VIEW=2;
    private void getMsgHistory(int historySize)throws InterruptedException {
        List<ConversationItemBean> conversationItemBeans=new ArrayList<>();
        showLogAndTsPrint("任务>>获取联系人消息记录");
        boolean isChangeToMainConversationAc=whatsAppTaskDealTool.isChangeConversationAcMain(true);
        if(isChangeToMainConversationAc){
            String nickName="test2";
            boolean isEnterInChatActivity=whatsAppTaskDealTool.enterInChatDetailsActivity(nickName);
            if(isEnterInChatActivity) {
                AccessibilityNodeInfo etNode = whatsAppTaskDealTool.findNodeFirstPlusById(WhatsAppNodeIdConfig.inputEtInChatAcId);
                AccessibilityNodeInfo sendNode = whatsAppTaskDealTool.findNodeFirstPlusById(WhatsAppNodeIdConfig.sendBtInChatAcId);
                if(etNode!=null&&sendNode!=null){
                    int lastConversationItemSize=-1;
                    while (conversationItemBeans.size()<historySize||lastConversationItemSize<conversationItemBeans.size()){
                        AccessibilityNodeInfo listViewNodeId = whatsAppTaskDealTool.findNodeFirstById(WhatsAppNodeIdConfig.chatListRootNodeId);
                        if(listViewNodeId==null||listViewNodeId.getChildCount()==0){
                            onTaskErr("无法获取聊天信息11");
                            return;
                        }
                        for(int i=listViewNodeId.getChildCount()-1;i>=0;i--) {
                            ConversationItemBean conversationItemBean=new ConversationItemBean();
                            int currentMessageType=WhatsAppTypeConfig.MESSAGE_TYPE_TEXT;
                            String myNickName="";
                            int isSelf=IS_SELF;
                            String messageText="";
                            String dateText="";
                            String placeNameText="";
                            int width=0;
                            int height=0;
                            AccessibilityNodeInfo viewGroup=listViewNodeId.getChild(i);
                            AccessibilityNodeInfo dateNode = whatsAppTaskDealTool.findNodeFirstById(viewGroup,WhatsAppNodeIdConfig.dateDividerHeaderInListNodeId);
                            if(dateNode!=null){
                                messageText=dateNode.getText().toString();
                                currentMessageType=WhatsAppTypeConfig.MESSAGE_TYPE_DATE_CENTER;
                                conversationItemBean.setMessage(messageText);
                                conversationItemBean.setCurrentMessageType(currentMessageType);
                                boolean hasInList=false;
                                if(!MyUtils.isEmpty(conversationItemBeans)){
                                    for(ConversationItemBean itemHasGet:conversationItemBeans){
                                        if(Objects.equals(itemHasGet,conversationItemBean)){
                                            hasInList=true;
                                            break;
                                        }
                                    }
                                }
                                if(!hasInList){
                                    conversationItemBeans.add(conversationItemBean);
                                }
                                continue;
                            }
                            AccessibilityNodeInfo itemNode = whatsAppTaskDealTool.findNodeFirstById(viewGroup,WhatsAppNodeIdConfig.chatListNodeId);
                            if(itemNode==null){
                                continue;
                            }

                            if(whatsAppUserInfo!=null){
                                myNickName=whatsAppUserInfo.getNickName();
                            }
                            Rect rect=new Rect();
                            itemNode.getBoundsInScreen(rect);
                            int left=rect.left;
                            int right=rect.right;
                            if(left==34){
                                isSelf=IS_TO_CHAT_USER;
                            }else if(right==686){
                                isSelf=IS_SELF;
                            }else{
                                isSelf=IS_OTHER_VIEW;
                            }

                            AccessibilityNodeInfo messageNodeId = whatsAppTaskDealTool.findNodeFirstById(itemNode, WhatsAppNodeIdConfig.messageTextNodeId);
                            AccessibilityNodeInfo dateNodeId = whatsAppTaskDealTool.findNodeFirstById(itemNode,WhatsAppNodeIdConfig.messageDateNodeId);
                            AccessibilityNodeInfo imageNodeId = whatsAppTaskDealTool.findNodeFirstById(itemNode,WhatsAppNodeIdConfig.messageImageNodeId);
                            AccessibilityNodeInfo imageWithTextNodeId = whatsAppTaskDealTool.findNodeFirstById(itemNode,WhatsAppNodeIdConfig.messageImageWithTextNodeId);
                            AccessibilityNodeInfo messagePlaceNameNodeId = whatsAppTaskDealTool.findNodeFirstById(itemNode,WhatsAppNodeIdConfig.messagePlaceNameNodeId);
                            AccessibilityNodeInfo messageVideoDurationNodeId = whatsAppTaskDealTool.findNodeFirstById(itemNode,WhatsAppNodeIdConfig.messageVideoDurationNodeId);
                            AccessibilityNodeInfo documentNodeId = whatsAppTaskDealTool.findNodeFirstById(itemNode,WhatsAppNodeIdConfig.messageDocumentNodeId);

                            if(dateNodeId!=null){
                                dateText=dateNodeId.getText().toString();
                            }


                            if(imageWithTextNodeId!=null){
                                currentMessageType=WhatsAppTypeConfig.MESSAGE_TYPE_IMAGE_WITH_TEXT;
                                if(messageVideoDurationNodeId!=null){
                                    currentMessageType=WhatsAppTypeConfig.MESSAGE_TYPE_VIDEO_WITH_TEXT;
                                }else{
                                    if(imageNodeId!=null){
                                        Rect imageRect=new Rect();
                                        imageNodeId.getBoundsInScreen(imageRect);
                                        width=imageRect.width();
                                        height=imageRect.height();
                                    }
                                }
                                messageText=imageWithTextNodeId.getText().toString();
                            }else if(documentNodeId!=null){
                                currentMessageType=WhatsAppTypeConfig.MESSAGE_TYPE_DOCUMENT;
                            }else if(messagePlaceNameNodeId!=null){
                                currentMessageType=WhatsAppTypeConfig.MESSAGE_TYPE_PLACE;
                                placeNameText=messagePlaceNameNodeId.getText().toString();
                            }else if(messageVideoDurationNodeId!=null){
                                currentMessageType=WhatsAppTypeConfig.MESSAGE_TYPE_VIDEO;
                            }else if(imageNodeId!=null){
                                currentMessageType=WhatsAppTypeConfig.MESSAGE_TYPE_IMAGE;
                                Rect imageRect=new Rect();
                                imageNodeId.getBoundsInScreen(imageRect);
                                width=imageRect.width();
                                height=imageRect.height();
                            }else{
                                currentMessageType=WhatsAppTypeConfig.MESSAGE_TYPE_TEXT;
                                if(messageNodeId!=null){
                                    messageText=messageNodeId.getText().toString();
                                }
                            }


                            if(isSelf==IS_SELF) {
                                conversationItemBean.setNickName("");
                            }else if(isSelf==IS_TO_CHAT_USER) {
                                conversationItemBean.setNickName(nickName);
                            }else if(isSelf==IS_OTHER_VIEW) {
                                conversationItemBean.setNickName("*未知控件*");
                            }

                            conversationItemBean.setUpdateDate(dateText);
                            conversationItemBean.setDirection(isSelf);
                            conversationItemBean.setPlaceText(placeNameText);
                            conversationItemBean.setMessage(messageText);
                            conversationItemBean.setCurrentMessageType(currentMessageType);
                            conversationItemBean.setImageWidth(width);
                            conversationItemBean.setImageHeight(height);

                            boolean hasInList=false;
                            if(!MyUtils.isEmpty(conversationItemBeans)){
                                for(ConversationItemBean itemHasGet:conversationItemBeans){
                                    if(Objects.equals(itemHasGet,conversationItemBean)){
                                        hasInList=true;
                                        break;
                                    }
                                }
                            }
                            if(!hasInList) {
                                if(imageNodeId!=null&&MyUtils.isEmpty(conversationItemBean.getImageUrl())){
                                    Rect rectNeedCrop=new Rect();
                                    imageNodeId.getBoundsInScreen(rectNeedCrop);
                                    if(rectNeedCrop.bottom<1170){
                                        int swipeTimes=0;
                                        while (rectNeedCrop.top<=160&&swipeTimes<5){
                                            swipeToBottom(1);
                                            Thread.sleep(500);
                                            imageNodeId = whatsAppTaskDealTool.findNodeFirstById(itemNode,WhatsAppNodeIdConfig.messageImageNodeId);
                                            imageNodeId.getBoundsInScreen(rectNeedCrop);
                                            swipeTimes++;
                                        }
                                        //图片或图文类型，准备截图
                                        File directory = BingTopDama.getRootDirectory();
                                        whatsAppChatImageName="whatsApp"+"_"+i;
                                        Bitmap bitmap = BingTopDama.takeScreenshotAndSaveToFilePath(whatsAppChatImageName);
                                        if(bitmap!=null) {
                                            try {
                                                ImageCropper.cropImage(bitmap, whatsAppChatImageName, rectNeedCrop);
                                                File file = new File(directory+"/"+whatsAppChatImageName+"_crop.jpg");
                                                if(file.exists()&&file.isFile()) {
                                                    File fileOld = new File(directory+"/"+whatsAppChatImageName+".jpg");
                                                    deleteFilePath(fileOld);
                                                    String url = HuaweiObsUtils.uploadFile(file);
                                                    conversationItemBean.setImageUrl(url);
                                                }
                                            }catch (Exception e){
                                                MsgTaskManger.showLog("出错："+e.getCause()+e.getMessage());
                                            }
                                        }
                                    }else{
                                        showLogAndTsPrint("滑动到底部了");
                                        continue;
                                    }
                                }
                                conversationItemBeans.add(conversationItemBean);
                            }
                        }
                        lastConversationItemSize=conversationItemBeans.size();
                        swipeToTop(1);
                        Thread.sleep(1000);
                    }
                    Collections.reverse(conversationItemBeans);
                    if(conversationItemBeans.size()>historySize){
                        conversationItemBeans=conversationItemBeans.subList((conversationItemBeans.size()-historySize),conversationItemBeans.size());
                    }
                    MsgTaskManger.showLog(GsonUtils.toJson(conversationItemBeans));
                    onTaskFinish();
                }else{
                    onTaskErr("无法进入聊天页面");
                }
            }else{
                onTaskErr("未匹配到对应联系人"+nickName+"，无法进入聊天页面");
            }
        }else{
            onTaskErr("无法切换到首页");
        }
    }


    /**
     * 任务做完后删除文件夹
     * @param folder
     */
    public  void deleteFilePath(File folder) {
        if (folder != null && folder.exists() && folder.isDirectory()) {
            File[] files = folder.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        deleteFilePath(file); // 递归删除子文件夹
                    } else {
                        file.delete(); // 删除文件
                    }
                }
            }
            folder.delete(); // 删除空文件夹
        } else {
            if (folder != null && folder.exists()){
                if(folder.isFile()){
                    folder.delete(); // 删除文件
                    return;
                }
            }
            // 文件夹不存在或者不是目录，做相应处理
            System.out.println("Folder does not exist or is not a directory");
            showLogAndTsPrint("删除文件夹失败");
        }
        //刷新相册
        new MediaRefreshHelper(BaseApp.app).scanFolder(folder);
    }


    private void swipeToBottom(int count) {
        showLogAndTsPrint("上滑一点");
        int startX = new Random().nextInt(50) + ScreenUtils.getAppScreenWidth() / 2;
        int endX = new Random().nextInt(20) + ScreenUtils.getAppScreenWidth() / 2;
        int startY = 280;
        int endY= 820;
        LogUtils.v("startY=" + startY + ",endY=" + endY + ",startX=" + startX + ",endX=" + endX);
        whatsAppTaskDealTool.swipe(startX, startY, endX, endY, 700);
        try {
            Thread.sleep(1000);
            count--;
            if (count > 0) {
                swipeToTop(count);
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public void swipeToTop(int count) {
        showLogAndTsPrint("上滑一屏");
        int startX = new Random().nextInt(50) + ScreenUtils.getAppScreenWidth() / 2;
        int endX = new Random().nextInt(20) + ScreenUtils.getAppScreenWidth() / 2;
        int startY = 280;
        int endY= 820;
        LogUtils.v("startY=" + startY + ",endY=" + endY + ",startX=" + startX + ",endX=" + endX);
        whatsAppTaskDealTool.swipe(startX, startY, endX, endY, 700);
        try {
            Thread.sleep(1000);
            count--;
            if (count > 0) {
                swipeToTop(count);
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 向某人发送聊天消息
     * @throws InterruptedException
     */
    private void sendMsgToUser() throws InterruptedException {
        showLogAndTsPrint("任务>>发送消息给某人");
        boolean isChangeToMainConversationAc=whatsAppTaskDealTool.isChangeConversationAcMain(true);
        if(isChangeToMainConversationAc){
            String nickName="test2";
            boolean isEnterInChatActivity=whatsAppTaskDealTool.enterInChatDetailsActivity(nickName);
            if(isEnterInChatActivity) {
                AccessibilityNodeInfo etNode = whatsAppTaskDealTool.findNodeFirstPlusById(WhatsAppNodeIdConfig.inputEtInChatAcId);
                AccessibilityNodeInfo sendNode = whatsAppTaskDealTool.findNodeFirstPlusById(WhatsAppNodeIdConfig.sendBtInChatAcId);
                if(etNode!=null&&sendNode!=null){
                    whatsAppTaskDealTool.setNodeText(etNode,"你好");
                    Thread.sleep(2000);
                    whatsAppTaskDealTool.clickXy(sendNode);
                    Thread.sleep(1000);
                    onTaskFinish();
                }else{
                    onTaskErr("无法进入聊天页面");
                }
            }else{
                onTaskErr("未匹配到对应联系人"+nickName+"，无法进入聊天页面");
            }
        }else{
            onTaskErr("无法切换到首页");
        }
    }


    /**
     * 更新用户信息
     * @throws InterruptedException
     */
    private void updateUserInfo() throws InterruptedException {
        showLogAndTsPrint("任务>>更新WhatsApp用户信息");
        boolean isChangeToMainConversationAc=whatsAppTaskDealTool.isChangeConversationAcMain(true);
        if(isChangeToMainConversationAc){
            whatsAppUserInfo=whatsAppTaskDealTool.getUserInfo();
            if(whatsAppUserInfo!=null){
                showLogAndTsPrint("获取用户成功："+whatsAppUserInfo.getNickName());
                MsgTaskManger.showLog("获取用户信息成功：\n"+whatsAppUserInfo);
                Thread.sleep(3000);
                onTaskFinish();
            }else{
                onTaskErr("获取用户信息失败");
            }
        }else{
            onTaskErr("无法切换到首页");
        }
    }

    public void updateConversationList() throws InterruptedException {
        showLogAndTsPrint("更新对话列表数据");
        boolean isChangeConversationAc=whatsAppTaskDealTool.isChangeConversationAcMain(true);
        if(isChangeConversationAc){
            List<ConversationItemBean> conversationItemBeans = whatsAppTaskDealTool.getConversationListInfo(1);
            nickNameNeedEdit.clear();
            for(ConversationItemBean conversationItemBean:conversationItemBeans){
                boolean isChangeNickName=checkIsChangeNickName(conversationItemBean.getNickName());
                if(!isChangeNickName){
                    nickNameNeedEdit.add(conversationItemBean.getNickName());
                }
            }
            MsgTaskManger.showLog(GsonUtils.toJson(conversationItemBeans));
            if(!MyUtils.isEmpty(nickNameNeedEdit)){
                showLogAndTsPrint("准备去修改昵称");
                //发送一个修改昵称的任务
                serverTaskDataBean.setTaskType(WhatsAppTypeConfig.WHATS_TYPE_EDIT_NICKNAME);
                TaskManager.getInstance().createWhatsTask(serverTaskDataBean);
            }
        }else{
            MsgTaskManger.showLog("无法切换到对话页面");
        }
    }

    private boolean checkIsChangeNickName(String nickName) {
        String reg="\\+\\d+-\\d+_+\\d*";
        Pattern pattern=Pattern.compile(reg);
        Matcher matcher = pattern.matcher(nickName);
        if(matcher.find()){
            return true;
        }
        return false;
    }


    /**
     * 空闲时更新对话列表数据
     * @throws InterruptedException
     */
    public static String jsonStr="";
    public synchronized void updateConversationListWhenFinishOrErr() throws InterruptedException {
        TaskManager.isDealingWhatsAppChatList=true;
        boolean isChangeConversationAc=whatsAppTaskDealTool.isChangeConversationAcMain(false);
        if(isChangeConversationAc){
            List<ConversationItemBean> conversationItemBeans = whatsAppTaskDealTool.getConversationListInfo(1);
            if(!jsonStr.equals(GsonUtils.toJson(conversationItemBeans))){
                jsonStr=GsonUtils.toJson(conversationItemBeans);
                nickNameNeedEdit.clear();
                for(ConversationItemBean conversationItemBean:conversationItemBeans){
                    boolean isChangeNickName=checkIsChangeNickName(conversationItemBean.getNickName());
                    if(!isChangeNickName){
                        nickNameNeedEdit.add(conversationItemBean.getNickName());
                    }
                }
                MsgTaskManger.showLog(GsonUtils.toJson(conversationItemBeans));
                if(!MyUtils.isEmpty(nickNameNeedEdit)){
                    showLogAndTsPrint("准备去修改昵称");
                    //发送一个修改昵称的任务
                    serverTaskDataBean.setTaskType(WhatsAppTypeConfig.WHATS_TYPE_EDIT_NICKNAME);
                    TaskManager.getInstance().createWhatsTask(serverTaskDataBean);
                }
                MsgTaskManger.showLog("数据有变化，更新消息");
                MsgTaskManger.showLog(jsonStr);
            }
        }
        TaskManager.isDealingWhatsAppChatList=false;
    }


    @Override
    public void onTaskFinish() throws InterruptedException {
        goToConversationAc();
        super.onTaskFinish();
    }

    @Override
    public void onTaskErr(){
        goToConversationAc();
        super.onTaskErr();
    }

    private void goToConversationAc() {
        try {
            whatsAppTaskDealTool.isChangeConversationAcMain(true);
            MsgTaskManger.showLog("切回对话列表页");
            Thread.sleep(200);
        } catch (InterruptedException e) {
            MsgTaskManger.showLog("无法回到对话列表页\n"+e.getMessage()+"|"+e.getCause());
        }
    }
}
